<?php
/**
 * Vendor2 MQTT 消息详细调试脚本
 * 检查 IMEI 是否存在、数据库连接等
 */

// 定义应用根目录
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

require __DIR__ . '/thinkphp/base.php';

use think\Db;
use app\service\MqttMessageHandler;
use app\service\MessageParser\MessageParserFactory;

echo "========== Vendor2 MQTT 消息详细调试 ==========\n\n";

// 测试数据
$topic = 'rziot/zftx_w06/861179035726231/result';
$messageData = [
    "c" => "zidianmao",
    "imei" => "861179035726231",
    "iccid" => "89860325247554801710",
    "ssid" => "MIFI-8915",
    "password" => "1234567890",
    "opname" => "46003",
    "dbm" => "-86",
    "simSwitch" => "2",
    "ip" => "192.168.100.1",
    "lac" => "30555",
    "version" => "JZ12SC_ZIDIANMAO_20251200_V1.0.0",
    "cell_id" => "27235605",
    "speed_downlink" => 0,
    "speed_uplink" => 0,
    "sn" => "86117903572623",
    "boot_time" => "1236643",
    "count" => "8",
    "hidden" => "0"
];

$imei = '861179035726231';

echo "【第一步】检查 IMEI 是否存在于数据库...\n";
try {
    $exists = Db::name('flow_wifi_imei')->where('IMEI', $imei)->count() > 0;
    echo $exists ? "✅ IMEI 存在于数据库\n" : "❌ IMEI 不存在于数据库\n";
    
    if ($exists) {
        $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
        echo "   现有记录: " . json_encode($record, JSON_UNESCAPED_UNICODE) . "\n";
    }
} catch (\Throwable $e) {
    echo "❌ 数据库查询失败: " . $e->getMessage() . "\n";
}

echo "\n【第二步】测试消息解析...\n";
$parser = MessageParserFactory::detect($topic, $messageData);
if ($parser) {
    $parsedData = $parser->parse($topic, $messageData);
    echo "✅ 消息解析成功\n";
    echo "   解析后的 IMEI: " . ($parsedData['IMEI'] ?? 'N/A') . "\n";
} else {
    echo "❌ 无法检测到解析器\n";
}

echo "\n【第三步】测试消息处理和保存...\n";
$handler = new MqttMessageHandler();
$result = $handler->handle($topic, $messageData);
echo $result ? "✅ 消息处理成功\n" : "❌ 消息处理失败\n";

echo "\n【第四步】强制保存到数据库...\n";
$handler->flush();
echo "✅ 已调用 flush() 方法\n";

echo "\n【第五步】检查数据库中是否有新数据...\n";
try {
    $newRecord = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
    if ($newRecord) {
        echo "✅ 数据库中找到记录\n";
        echo "   更新时间: " . ($newRecord['update_time'] ?? 'N/A') . "\n";
        echo "   ICCID: " . ($newRecord['iccid'] ?? 'N/A') . "\n";
        echo "   信号强度: " . ($newRecord['signal_strength'] ?? 'N/A') . "\n";
    } else {
        echo "❌ 数据库中没有找到记录\n";
    }
} catch (\Throwable $e) {
    echo "❌ 查询失败: " . $e->getMessage() . "\n";
}

echo "\n========== 调试完成 ==========\n";

